﻿using Avalonia;
using Avalonia.ReactiveUI;
using CefGlue.Avalonia;
using CefGlue.Avalonia.Http;
using System;
using System.Linq;
using TouchSocket.Core;
using TouchSocket.Rpc;
using TouchSocket.Sockets;
using Xilium.CefGlue;

namespace CefGlue.AvaloniaTest
{
    internal class Program
    {

        // Initialization code. Don't use any Avalonia, third-party APIs or any
        // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
        // yet and stuff might break.
        [STAThread]
        public static void Main(string[] args)
        {   
            if (CefRuntimeExtension.IsSecondaryProcess(args))
            {
                CefRuntimeExtension.RunSecondaryProcess(args);
                return;
            }
            //CommonConst.IsDebug = OperatingSystem.IsMacOS() ? true : false;
            CommonConst.HttpPort = 4600;
            try
            {
                TouchSocket.Http.HttpService httpService = new TouchSocket.Http.HttpService();
                StartHttpServer(httpService);
                BuildAvaloniaApp(args)
                .StartWithClassicDesktopLifetime(args);
                StopHttpServer(httpService);
            }
            catch (Exception ex) 
            {
                LogHelper.Error(ex, ex.Message);
            }
        }
        // Avalonia configuration, don't remove; also used by visual designer.
        public static AppBuilder BuildAvaloniaApp(string[] args)
            => AppBuilder.Configure<App>()
                .UsePlatformDetect()
                .UseSkia()
                .WithInterFont()
                .LogToTrace()
                .ConfigureCefGlue(args)
                .UseReactiveUI();

        private static void StartHttpServer(TouchSocket.Http.HttpService httpService)
        {
            httpService.Setup(new TouchSocketConfig()

                   .SetListenIPHosts(new IPHost(CommonConst.HttpPort))
                   .ConfigureContainer(a =>
                   {
                       a.AddConsoleLogger();
                       a.AddRpcStore(c =>
                        {
                            c.RegisterServer<TouchWebApiServer>();//注册服务
                        });
                   }
                   ).ConfigurePlugins(a =>
                   {
                       a.UseCheckClear();
                       a.UseWebApi();//启用WebApi
                       a.UseDefaultHttpServicePlugin();
                   }));


            httpService.Start();
        }

        private static void StopHttpServer(TouchSocket.Http.HttpService httpService)
        {
            httpService.Stop();
        }
       
        
    }
}